package cn.i7baozh.starter.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 全局过滤器 -- 不需要额外进行配置
 *
 * @author : baoqi.zhang
 * @date :   2022/4/22 20:47
 */
@Slf4j
@Component
public class GlobalXSSRejectFilter implements GlobalFilter, Ordered {

    private static final String CODE = "code";

    private static final String MESSAGE_KEY = "message";

    private static final String CONTENT_TYPE = "content-type";

    private static final String MESSAGE = "当前请求存在恶意脚本, 拒绝访问。";

    @Autowired
    private ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpMethod method = request.getMethod();
        URI uri = request.getURI();
        if (HttpMethod.GET == method) {
            String rawQuery = uri.getRawQuery();
            if (StringUtils.isBlank(rawQuery)) {
                return chain.filter(exchange);
            }
            String paramString = rawQuery.replaceAll("[\u0000\n\r]", "");
            if (StringUtils.isBlank(paramString)) {
                return chain.filter(exchange);
            }
            String lowerValue = URLDecoder.decode(paramString, StandardCharsets.UTF_8.displayName()).toLowerCase();
            for (Pattern pattern : PATTERNS) {
                if (pattern.matcher(lowerValue).find()) {
                    return returnXssError(exchange);
                }
            }
        }
        //正常输出信息
        return chain.filter(exchange);
    }


    private Mono<Void> returnXssError(ServerWebExchange exchange) {

        ServerHttpResponse response = exchange.getResponse();
        Map<String, Object> jsonObject = new HashMap<>();
        jsonObject.put(CODE, HttpStatus.BAD_REQUEST.value());
        jsonObject.put(MESSAGE_KEY, MESSAGE);

        response.getHeaders().add(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String result = "";
        try {
            result = objectMapper.writeValueAsString(jsonObject);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        DataBuffer wrap = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        //异常输出信息
        return response.writeWith(Flux.just(wrap));
    }

    //值越小 优先级越高
    @Override
    public int getOrder() {
        return 0;
    }

    private static final Pattern[] PATTERNS = {
            // Avoid anything in a <script> type of expression
            Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),
            // Avoid anything in a src='...' type of expression
            Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            // Remove any lonesome </script> tag
            Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
            // Avoid anything in a <iframe> type of expression
            Pattern.compile("<iframe>(.*?)</iframe>", Pattern.CASE_INSENSITIVE),
            // Remove any lonesome <script ...> tag
            Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            // Remove any lonesome <img ...> tag
            Pattern.compile("<img(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            // Avoid eval(...) expressions
            Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            // Avoid expression(...) expressions
            Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            // Avoid javascript:... expressions
            Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
            // Avoid vbscript:... expressions
            Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
            // Avoid onload= expressions
            Pattern.compile("on(load|error|mouseover|submit|reset|focus|click)(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
    };
}
